<template>
  <div class="container login-container">
    <div class="title">
      <p>Hi~</p>
      <p>欢迎来到云木屋</p>
    </div>
    <form>
      <div class="form-item">
        <div class="form-inp">
          <img src="../assets/login/phone.png" />
          <input type="Number" ref="phone" placeholder="请输入手机号" v-model="phone" />
        </div>
        <div class="form-icon">
          <img
            src="../assets/login/delete.png"
            v-show="phone"
            class="delete"
            @click="handleDeleteVal('phone')"
          />
        </div>
      </div>
      <div class="form-item">
        <div class="form-inp">
          <img src="../assets/login/password.png" />
          <input
            :type="isRead ? 'text' : 'password'"
            ref="password"
            placeholder="请输入密码"
            v-model="password"
          />
        </div>
        <div class="form-icon">
          <img
            src="../assets/login/delete.png"
            v-show="password"
            class="delete"
            @click="handleDeleteVal('password')"
          />
          <img
            v-show="password && !isRead"
            src="../assets/login/close_eye.png"
            alt
            @click="handleReadPwd"
          />
          <img
            v-show="password && isRead"
            src="../assets/login/open_eye.png"
            alt
            @click="handleReadPwd"
          />
        </div>
      </div>
      <div class="edit-pwd">
        <span @click="handleForWord">忘记密码？</span>
      </div>
      <button @click.prevent="handleLogin" :class="phone&&password ? 'login active' : 'login' ">立即登录</button>
    </form>
    <div class="footer">
      <p>
        没有账号？
        <span @click="toSignUp">立即注册</span>
      </p>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from "@/api/user";
import { getToken, setToken, removeToken, setWebToken } from "@/utils/auth";
import { Notify } from "vant";
import { getloginkey, login } from "@/api/login";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      phone: "",
      // phone: "15112765331",
      password: "",
      // password: "123456",
      isRead: false,
      loginKey: "",
      refreshFlag: null,
    };
  },
  created() {
    removeToken();
    this._getloginkey();
    console.log(process.env.VUE_APP_BASE_YMW);
    if (this.toLogin) {
      clearTimeout(this.toLogin);
    }
    this.refreshFlag = setTimeout(() => {
      this._getloginkey();
    }, 300000);
  },
  computed: {
    ...mapGetters(["toLogin"]),
  },
  watch: {
    phone(val) {
      if (val.length >= 11) {
        this.phone = val.substring(0, 11);
      }
    },
  },
  methods: {
    // 获取登录key
    _getloginkey() {
      let params = {
        reqdata: JSON.stringify({ t: new Date().getTime() }),
      };
      getloginkey(params).then((res) => {
        console.log("登录KEY res", res);
        if (res.code == 1) {
          this.loginKey = res.data.key;
          console.log("登录KEY", this.loginKey);
        } else {
          console.log(res.msg);
        }
      });
    },
    // 登录
    async handleLogin() {
      const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (this.phone == "") {
        // this.$toast("请输入手机号");
        Notify({ type: "warning", message: "请输入手机号" });
      } else if (this.phone && !reg.test(this.phone)) {
        Notify({ type: "warning", message: "手机号码格式错误" });
      } else if (this.password == "") {
        Notify({ type: "warning", message: "请输入密码" });
      } else if (this.loginKey == "") {
        Notify({ type: "warning", message: "登录凭证获取失败，请稍后重试" });
        this._getloginkey();
      } else {
        try {
          this.$toast.loading({
            duration: 0,
            message: "正在登陆",
            forbidClick: true,
            loadingType: "spinner",
          });
          let req_data = {
            reqdata: JSON.stringify({
              t: `${new Date().getTime()}`,
              mobile: this.phone,
              password: this.password,
              loginKey: this.loginKey,
            }),
          };
          let loginRes = await login(req_data);
          console.log("loginRes", loginRes);
          this.$toast.clear();
          if (loginRes.code == 1) {
            setToken(decodeURI(loginRes.token));
            setWebToken(decodeURI(loginRes.token));
            this.$router.push({
              path: "/",
            });
            clearTimeout(this.refreshFlag);
          } else if (loginRes.code == 10114) {
            this.$toast.fail("账号或密码错误，请重试");
            this._getloginkey();
            return false;
          } else {
            this.$toast.fail("登陆失败！请重试");
            this._getloginkey();
            return false;
          }

          // setToken(decodeURI("3%252FG9kjGc%252B1I%253D"));
          // setToken(decodeURI("PCvjdFN%252F0iM%253D"));
          // let token = getToken();

          // getUserInfo(token).then(res => {
          //   if (res.code == 1) {
          //     this.$toast.clear();
          //     this.$router.push({
          //       path: "/"
          //     });
          //   } else {
          //     console.log(res);
          //     this.$toast.fail("登陆失败");
          //   }
          // });
        } catch (error) {
          console.log("获取登录key失败", error);
          this.$toast.clear();
          this._getloginkey();
        }
      }
    },
    //忘记密码
    handleForWord() {
      this.$router.push({
        path: "/edit_pwd",
      });
    },
    // 删除输入框内容
    handleDeleteVal(str) {
      this[str] = "";
      this.$refs[str].focus();
      this.isRead = false;
    },
    handleReadPwd() {
      this.isRead = !this.isRead;
    },
    // 前往注册
    toSignUp() {
      this.$router.push({
        name: "signUp",
      });
    },
  },
};
</script>
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #2d3a4b;
$light_gray: #333;
$cursor: #333;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  input {
    background: transparent;
    border: none;
    -webkit-appearance: none;
    border-radius: 0px;
    color: $light_gray;
    caret-color: $cursor;
    &:-webkit-autofill {
      box-shadow: 0 0 0px 1000px transparent inset !important;
      -webkit-text-fill-color: $cursor !important;
      background-color: transparent;
      background-image: none;
      transition: background-color 50000s ease-in-out 0s; //背景色透明  生效时长  过渡效果  启用时延迟的时间
    }
  }
}
</style>

<style scoped lang='scss'>
.container {
  width: 100vw;
  padding: 110px 50px 0 50px;
  .title {
    text-align: left;
    font-size: 50px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(17, 17, 17, 1);
    margin-bottom: 96px;
    > p:nth-of-type(1) {
      margin-bottom: 30px;
    }
  }
  .form-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 22px 0;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 68px;
    text-align: initial;
    .form-inp {
      width: 76%;
      display: flex;
      input {
        flex: 1;
      }
    }
    .form-icon {
      // width: 24%;
      width: 160px;
    }
    > div:nth-of-type(1) {
      > img:nth-of-type(1) {
        width: 26px;
        height: 36px;
        vertical-align: middle;
        margin-right: 22px;
      }
    }
    > div:nth-of-type(2) {
      > img {
        width: 30px;
        height: 20px;
        vertical-align: middle;
        margin-left: 50px;
      }
      > .delete {
        width: 26px;
        height: 26px;
      }
    }

    > input {
      font-size: 30px;
      color: #111111;
      &::placeholder {
        color: #cccccc;
      }
    }
    &:nth-of-type(2) {
      margin-bottom: 30px;
    }
  }
  .edit-pwd {
    text-align: right;
    font-size: 28px;
    font-family: PingFang SC;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
    margin-bottom: 44px;
  }
  .login {
    width: 650px;
    height: 90px;
    line-height: 90px;
    font-size: 30px;
    color: #fff;
    margin-top: 50px;
    background: linear-gradient(
      90deg,
      rgba(255, 212, 154, 1),
      rgba(255, 191, 163, 1)
    );
    border-radius: 4px;
    &.active {
      background: linear-gradient(
        90deg,
        rgba(255, 147, 3, 1),
        rgba(254, 96, 24, 1)
      );
    }
  }
  .footer {
    font-size: 28px;
    color: #999;
    position: fixed;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    span {
      color: #387eff;
    }
  }
}
</style>
